package org.sais.exscanner;

import android.content.Context;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

public class MediaScannerNotifier extends AsyncTask<Void, Void, Void> implements MediaScannerConnectionClient {
	
	private MediaScannerConnection mConnection;
	private String mPath;
	private String mMimeType;
	private boolean mScanCompleted = false;
	private ScanCompletedListener mListener;

	public MediaScannerNotifier(Context context, String path, String mimeType) {
		this(context, path, mimeType, null);
	}

	public MediaScannerNotifier(Context context, String path, String mimeType, ScanCompletedListener listener) {
		if (mimeType == null) {
			return;
		}
		if ("".equals(mimeType)) {
			return;
		}
		if (path.contains("/.")) {
			return;
		}

		Log.i(ScanService.TAG, "Scanning " + mimeType + ": " + path);
		
		mPath = path;
		mMimeType = mimeType;
		mListener = listener;
		mConnection = new MediaScannerConnection(context, this);
		execute();
	}

	public void onMediaScannerConnected() {
		mConnection.scanFile(mPath, mMimeType);
	}

	public boolean isScanCompleted() {
		return mScanCompleted;
	}

	public void onScanCompleted(String path, Uri uri) {
		Log.i(ScanService.TAG, "Completed scanning " + path);
		mScanCompleted = true;
		mListener.onComplete(uri);
		mConnection.disconnect();
	}

	public interface ScanCompletedListener {
		public void onComplete(Uri uri);
	}

	@Override
	protected Void doInBackground(Void... params) {
		mConnection.connect();
		return null;
	}
}